package com.example.jnet.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class ToolUtils {
    private static Logger logger = LoggerFactory.getLogger(ToolUtils.class);

    public static int bytes2Int(byte[] bytes) {
        int result = 0;
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            DataInputStream dis = new DataInputStream(bais);
            result = dis.readInt();
        } catch (Exception e) {
            logger.error("e: " + e.getMessage(), e);
        }

        return result;
    }

    public static long bytes2Long(byte[] bytes) {
        long result = 0;
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            DataInputStream dis = new DataInputStream(bais);
            result = dis.readLong();
        } catch (Exception e) {
            logger.error("e: " + e.getMessage(), e);
        }

        return result;
    }

    public static String bytes2Str(byte[] bytes) {
        String result = null;
        try {
            if (bytes != null) {
                result = new String(bytes, "UTF-8");
            }
        } catch (Exception e) {
            logger.error("e:" + e.getMessage(), e);
        } finally {
            return result;
        }
    }

    public static byte[] int2bytes(int value, int number) {
        byte[] result = new byte[number];
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeInt(value);

            result = baos.toByteArray();
        } catch (Exception e) {
            logger.error("e:" + e.getMessage(), e);
        } finally {
            return result;
        }
    }

    public static byte[] long2bytes(long value, int number) {
        byte[] result = new byte[number];
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeLong(value);

            result = baos.toByteArray();
        } catch (Exception e) {
            logger.error("e: " + e.getMessage(), e);
        }

        return result;
    }

    public static byte[] getTunnelId() {
        byte[] tunnelId = new byte[8];
        try {
            long now = System.currentTimeMillis();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeLong(now);

            tunnelId = baos.toByteArray();
        } catch (Exception e) {
            logger.error("e:" + e.getMessage(), e);
        } finally {
            return tunnelId;
        }
    }
}
